#include <cstdio>
#include <cstdlib>
#include<iostream>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<cstring>
#include<string.h>
#include <unistd.h>

int main(int argc,const char* argv[])
{
    if(argc!=3){
        return 1;
    }
    int sock=socket(AF_INET, SOCK_DGRAM, 0);
    if(sock < 0)
    {
        perror("socket");
        return 1;
    }
    struct sockaddr_in server;
    server.sin_family=AF_INET;
    server.sin_port=htons(atoi(argv[2]));
    server.sin_addr.s_addr=inet_addr(argv[1]);
    int ret=bind(sock, (struct sockaddr*)&server, sizeof(server));
    if(ret < 0)
    {
        perror("bind()");
        return 1;
    }
    ret=listen(sock, 10);
    if(ret < 0)      
    {
        perror("listen");
        exit(-1);
    }
    while(true)
    {
        struct sockaddr_in client_addr;
        socklen_t len=sizeof(client_addr);
        int client_sock=accept(sock, (struct sockaddr*)&client_addr, &len);
        if(client_sock < 0)
        {
            perror("accept()");
            exit(-2);
        }
        char inbuffer[1024];
        ssize_t s=read(client_sock, &inbuffer, sizeof(inbuffer));
        if(s < 0){
            exit(1);
        }
        printf("[Request]:%s",inbuffer);
        char buffer[1024]={0};
        const char* hello="<h1>hello world<h1>";
        //snprintf(buffer,"HTTP/1.0 200 OK\nContent-Length:%lu %s",strlen(hello),hello);
        snprintf(buffer, sizeof(buffer), "HTTP/1.0 200 OK\nContent-Length:%lu %s", hello);
        write(client_sock, buffer, sizeof(buffer));
    }
    return 0;
}